from django.http import HttpResponsePermanentRedirect, Http404

from projects.models import Project, Release
from news.models import News
from profiles.models import Profile
from cab.models import Snippet

ALPHABETS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

tiny4class = {News:"n", Project:"p", Release:"r", Snippet:"s", Profile:"u"}
class4tiny = dict((v, k) for k, v in tiny4class.iteritems())

def get_tiny_url(obj):
    if obj.__class__ in tiny4class:
        prefix = tiny4class[obj.__class__]
        n = len(ALPHABETS)
        rv = ""
        num = obj.id
        while num != 0:
            rv = ALPHABETS[num % n] + rv
            num /= n
        return "/%s/%s/" % (prefix, rv)
    raise ValueError, "No tiny url function for class '%s'" % obj.__class__


def old_project(request, project_id):
    if request.method == "GET" and "release_id" in request.GET:
        try:
            release = Release.objects.get(pk=int(request.GET["release_id"]))
            if release.project.id == project_id:
                return HttpResponsePermanentRedirect(release.get_absolute_url())
        except (Release.DoesNotExist, ValueError):
            pass
    try:
        project = Project.objects.get(pk=project_id)
        return HttpResponsePermanentRedirect(project.get_absolute_url())
    except Project.DoesNotExist:
        raise
            
def generic_tiny_url(request, tiny_bit, obj_id):
    if not tiny_bit in class4tiny:
        raise Http404
    query = class4tiny[tiny_bit].objects
    n = len(ALPHABETS)
    rv = pos = 0
    charlist = list(obj_id)
    charlist.reverse()
    for char in charlist:
        rv += ALPHABETS.find(char) * n**pos
        pos += 1
    if query.filter(pk=rv):
        url = query.filter(pk=rv)[0].get_absolute_url()
        return HttpResponsePermanentRedirect(url)
    else:
        raise Http404
